<template>
  <div>
    <el-button type="primary" @click="created">创建数据库</el-button>
    <el-button type="primary" @click="getIndexed">获取数据库数据</el-button>
  </div>
</template>

<script>
export default {
  data() {
    return {};
  },
  methods: {
    // 创建数据库
    created() {
      const request = window.indexedDB.open("indexedDBTest");

      request.onupgradeneeded = function (event) {
        console.log("当前数据库更新了", event);
        var db = event.target.result;

        var objectStore = db.createObjectStore("table1", {
          keyPath: "id",
          autoIncrement: true,
        });

        objectStore.createIndex("name", "name", { unique: false });
      };

      request.onsuccess = function (event) {
        //request === event.target;
        console.log("当前数据库连接完成", event);
        var db = event.target.result;

        var transaction = db.transaction(["table1"], "readwrite");

        var objectStore = transaction.objectStore("table1");

        objectStore.add({ name: "a", age: 10 });
        objectStore.add({ name: "b", age: 20 });
      };
      request.onerror = function (event) {};
    },
    // 获取数据库数据
    getIndexed() {
      console.log("开始获取数据库数据");
      const request = window.indexedDB.open("indexedDBTest");
      request.onsuccess = function (event) {
        console.log("获取数据连接成功");
        var db = event.target.result;
        var transaction = db.transaction(["table1"], "readwrite");

        var objectStore = transaction.objectStore("table1");
        var index = objectStore.index("name");
        console.log(index,"查看index对象")

        // 第一种，get方法
        index.get("c").onsuccess = function (event) {
          console.log("获取到的name为a的数据")
          console.log(event.target.result);
        };
        var request = objectStore.get(1);

        request.onsuccess = function (event) {
          // 对 request.result 做些操作！
          console.log(request.result, "获取主键为1的数据");
        };

        request.onerror = function (event) {
          // 错误处理!
        };

        var request2 = objectStore.openCursor();

        request2.onsuccess = function (event) {
          var cursor = event.target.result;
          if (cursor) {
            // 使用Object.assign方法是为了避免控制台打印时出错
            console.log(Object.assign(cursor.value));
            cursor.continue();
          }
        };

        request2.onerror = function (event) {
          // 错误处理!
        };

        
      };
    },
  },
};
</script>

<style>
</style>